//
//  MyVoiceViewController.m
//  NewChat
//
//  Created by 马欢 on 16/2/28.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "MyVoiceViewController.h"
#import "MHDataHelper.h"
#import "FindModel.h"
#import "SKXFriendManager.h"
#import "SKXRongCloudManager.h"
#import "RecordProgress.h"
#import "PlayerManager.h"


#define RECORD [SKXFriendManager sharaFriendManager]
#define HELPER [MHDataHelper shareDataHelper]
static int i = 0;

@interface MyVoiceViewController ()

@property (weak, nonatomic) IBOutlet UIButton *myVoiceBtn;
@property (weak, nonatomic) IBOutlet UIButton *repeatBtn;
@property (weak, nonatomic) IBOutlet UITextField *topicMessage;
@property (weak, nonatomic) IBOutlet UILabel *voiceLabel;
@property (nonatomic,strong)NSURL *voiceURL;
@property (nonatomic,strong)UIImageView *backgroundView;
//录音动画
@property (nonatomic , strong)NSTimer *timer;

@property (weak, nonatomic) IBOutlet RecordProgress *progressVoice;

@property (nonatomic,assign)CGFloat progressNew;

@end

@implementation MyVoiceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    录音动画
    
    self.progressNew = 0;
    self.progressVoice.totalTime = 60;
    self.progressVoice.layer.masksToBounds = YES;
    self.progressVoice.layer.cornerRadius = self.progressVoice.frame.size.width/2.0;
    self.backgroundView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    self.backgroundView.image = [UIImage imageNamed:@"100.jpg"];
    [self.view addSubview:self.backgroundView];
    [self.view sendSubviewToBack:self.backgroundView];
//    准备录音
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.title = @"新建话题";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发布" style:(UIBarButtonItemStylePlain) target:self action:@selector(newTopic)];
    self.myVoiceBtn.layer.cornerRadius = self.myVoiceBtn.frame.size.width/2.0;
    [self.myVoiceBtn addTarget:self action:@selector(myVoice:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.repeatBtn addTarget:self action:@selector(repeat:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.repeatBtn setHidden:YES];
}
//我的
-(void)myVoice:(UIButton *)sender{
    if ([self.voiceLabel.text isEqualToString:@"点击录音..."]) {
        //开始录音
        [RECORD startRecordVoiceWithFileName:nil];
        [[PlayerManager defaultManager] pausePlay];
        [self addTimer];//添加定时器
        self.voiceLabel.text = @"正在录音...";
        [sender setTitle:@"停止" forState:(UIControlStateNormal)];
    }else if ([self.voiceLabel.text isEqualToString:@"正在录音..."]){
        self.voiceLabel.text = @"";
        [sender setTitle:@"播放" forState:(UIControlStateNormal)];
        //停止录音，保存url
        i = 2;
        [self cancelTimer];//取消定时器
        [RECORD stopRecordVoiceWithBlock:^(NSString *path) {
            self.myVoicePath = path;
        }];
        
        [self.repeatBtn setHidden:NO];
    }else if ([self.voiceLabel.text isEqualToString:@""]){
        self.voiceLabel.text = @"正在播放";
        [sender setTitle:@"停止" forState:(UIControlStateNormal)];
        //播放===========================
        [SKXFriendManager playVoiceWith:self.myVoicePath WithLabel:nil];
        [self.repeatBtn setHidden:YES];
    }else if ([self.voiceLabel.text isEqualToString:@"正在播放"]){
        self.voiceLabel.text = @"";
        [sender setTitle:@"播放" forState:(UIControlStateNormal)];
        //停止播放
        [[SKXRongCloudManager sharaManager] skxStopPlay];//停止播放
        [SKXFriendManager stop];
        [self.repeatBtn setHidden:NO];
    }
}
//重新录制 录音
-(void)repeat:(UIButton *)sender{
    if ([self.voiceLabel.text isEqualToString:@""]) {
        [sender setHidden:YES];
    }
    NSLog(@"重新录语音");
    self.voiceLabel.text = @"正在录音...";
    [self.myVoiceBtn setTitle:@"停止" forState:(UIControlStateNormal)];
    
    //开始录音
    [self cancelTimer];//取消定时器，重新录
    self.progressNew =0;
    [RECORD startRecordVoiceWithFileName:nil];
    [self addTimer];//添加定时器
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//返回上一层
-(void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
//发布 新话题
-(void)newTopic{

    if (i == 2) {//file是否存在 不存在不保存
        if ([self.myVoicetype isEqualToString:@"topic"]) {//发布话题进来的
            //    存储数据
            FindModel *find = [FindModel object];
            //    话题
            find.topicMessage = self.topicMessage.text;
            //    昵称
            find.owner =[AVUser currentUser];
            //    发布的话题类型
            find.mHTopicType = self.MHTopicType;
            //    存语音
            AVFile *file = [AVFile fileWithName:nil contentsAtPath: self.myVoicePath];
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [find setObject:file.url forKey:@"messageVoice"];
                    [find saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        NSLog(@"============%@",file.url);//返回一个唯一的 Url地址
                        if (succeeded) {
                            NSLog(@"成功");
                        }else{
                            NSLog(@"失败");
                        }
                    }];
                }
            }];
        }
        else{//录制个性签名
            AVUser *user = [AVUser currentUser];
            AVFile *file = [AVFile fileWithName:nil contentsAtPath: self.myVoicePath];
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [user setObject:file.url forKey:@"myVoice"];
                    [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        NSLog(@"============%@",file.url);
                        if (succeeded) {
                            NSLog(@"成功");
                        }else{
                            NSLog(@"失败");
                        }
                    }];
                }
            }];
        }
    }//判断是否file为空
//    ＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝
    i = 0;
    [self backAction];
}

//==================一般不改==============================
//view将要出现 给背景色
-(void)viewWillAppear:(BOOL)animated{
    self.view.backgroundColor = [UIColor whiteColor];
    
    if ([self.myVoicetype isEqualToString:@"topic"]) {
        self.navigationItem.title = @"新建话题";
    }else{
        self.navigationItem.title = @"个性签名";
    }
}
//===录音动画===
//添加定时器
-(void)addTimer{
    self.timer = [NSTimer timerWithTimeInterval:0.05 target:self selector:@selector(startAction) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
//取消定时器
-(void)cancelTimer{
    [self.timer invalidate];
    self.timer = nil;
}
//定时器方法
//-(void)startAction{
//    self.progressVoice.progress += 0.05;
//    if (self.progressVoice.progress >= 60) {
//        [self cancelTimer];
//    }
//}
-(void)startAction{
    
    self.progressNew +=0.05;
    
    [self.progressVoice newProgress:self.progressNew];
    
    if (self.progressNew >= 60) {
        [self cancelTimer];
        
        self.progressNew = 0;
    }
}

//开始录制
-(void)recordStart:(UIButton *)sender { 
    NSLog(@"打开定时器");
    [self addTimer];
}

//点击空白回收键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.topicMessage resignFirstResponder];
}
@end
